const mysql=require('mysql');
const argv=process.argv;
const http=require('http');
const path=require('path');
const fs=require('fs');

var con=mysql.createConnection({
    host:'192.168.213.144',
    port:3306,
    user:'root',
    password:'ddd',
    database:'chapters'
})

http.createServer((req,res)=>{
    var urlObj=new URL(req.url,'http://localhost:8084');
    var pathName=urlObj.pathname;
    if(pathName=='/'){
        var listPath=path.join(__dirname,'/chapterList.html');
        var listContent=fs.readFileSync(listPath);
        res.writeHead(200,{'content-type':'text/html;charset=utf-8'});
        res.write(listContent);
        res.end();
    }else if(pathName.indexOf('/css/')==0){
        var fileName=pathName.slice(5);
        var filePath=path.join(__dirname,`/css/${fileName}`);
        var fileContent=fs.readFileSync(filePath);
        res.writeHead(200,{'content-type':'text/css'});
        res.write(fileContent);
        res.end();
    }else if(pathName.indexOf('/images/')==0){
        var fileName=pathName.slice(8);
        var filePath=path.join(__dirname,`/images/${fileName}`);
        var fileContent=fs.readFileSync(filePath);
        res.writeHead(200,{'content-type':'image/jpeg'});
        res.write(fileContent);
        res.end();
    }else if(pathName=='/getChapterList'){
        var selectSql='select * from chapters';
        con.query(selectSql,(err,result)=>{
            if(err){
                console.log(err);
            }else{
                res.writeHead(200,{'content-type':'text/plain'});
                res.write(JSON.stringify(result));
                res.end();
            }
        })
    }else if(pathName.indexOf('/getDetail')==0){
        var chapterId=urlObj.searchParams.get('chapterId');
        var selectSql='select chapterName,publishTimer,author,views,chapterContent from chapters where chapterId=?';
        con.query(selectSql,[chapterId],(err,result)=>{
            if(err){
                console.log(err);
            }else{
                res.setHeader('Access-Control-Allow-Origin','*');
                res.writeHead(200,{'content-type':'text/plain'});
                res.write(JSON.stringify(result));
                res.end();
            }
        })
    }
}).listen(8084);
